package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Override
    public CourseTeacher saveOrEdit(Long companyId, CourseTeacher courseTeacherDto) {
        if (courseTeacherDto==null){
            XueChengPlusException.cast("参数为空");
        }
        if(companyId==null){
            XueChengPlusException.cast("机构ID为空");
        }
        CourseBase courseBase = courseBaseMapper.selectById(courseTeacherDto.getCourseId());
        if(courseBase==null){
            XueChengPlusException.cast("课程ID不存在");
        }
        Long companyId1 = courseBase.getCompanyId();
        if(!companyId1.equals(companyId)){
            XueChengPlusException.cast("只允许向机构所属课程添加老师");
        }

        //是否已经存在老师
        CourseTeacher courseTeacher = courseTeacherMapper.selectById(courseTeacherDto.getId());
        if(courseTeacher==null){
            courseTeacher = new CourseTeacher();
            courseTeacher.setCreateDate(LocalDateTime.now());
            BeanUtils.copyProperties(courseTeacherDto,courseTeacher);
            courseTeacherMapper.insert(courseTeacher);
            return courseTeacher;
        }
        //已存在更新
        BeanUtils.copyProperties(courseTeacherDto,courseTeacher);
        courseTeacherMapper.updateById(courseTeacher);
        return courseTeacher;
    }

    @Override
    public List<CourseTeacher> selectTeacherList(Long courseId) {
        return courseTeacherMapper.selectList(new LambdaQueryWrapper<CourseTeacher>()
                .eq(CourseTeacher::getCourseId,courseId));
    }

    @Override
    public void deleteTeacherInfo(Long courseId, Long courseTeacherId, Long companyId) {
        chechCompanyId(companyId,courseId,"只允许向机构自己的课程中删除教师信息");
        courseTeacherMapper.deleteById(courseTeacherId);
    }

    private void  chechCompanyId(Long companyId,Long courseId,String message){
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast(message);
        }
    }
}
